package com.qingzhu.messageserver.domain.entity

import com.qingzhu.common.domain.shared.msg.constant.CreatorType
import com.qingzhu.common.util.JsonUtils
import com.qingzhu.common.util.toJson
import org.springframework.data.cassandra.core.cql.PrimaryKeyType
import org.springframework.data.cassandra.core.mapping.PrimaryKey
import org.springframework.data.cassandra.core.mapping.PrimaryKeyClass
import org.springframework.data.cassandra.core.mapping.PrimaryKeyColumn
import org.springframework.data.cassandra.core.mapping.Table
import java.time.Instant

@Table("chat_msg")
data class ChatMessagePO(
    @PrimaryKey
    val chatMessageKey: ChatMessageKey,
    /** ChatMessage uuid */
    val uuid: String,
    val createdAt: Instant = Instant.now(),
    /** 会话id */
    var conversationId: Long?,
    /** 消息来源 (服务器设置) */
    var from: Long,
    /** 消息送至 */
    var to: Long,
    /** 消息类型 接收者类型 */
    val type: CreatorType,
    /** 创建者类型 */
    val creatorType: CreatorType,
    /** 内容 */
    val content: String,
    /** 昵称 */
    val nickName: String? = null,
) {
    constructor(chatMessage: ChatMessage, ownerId: Long) : this(
        ChatMessageKey(
            organizationId = chatMessage.organizationId,
            ownerId = ownerId.toString(),
            seqId = chatMessage.seqId,
        ),
        chatMessage.uuid,
        chatMessage.createdAt,
        chatMessage.conversationId,
        chatMessage.from,
        chatMessage.to,
        chatMessage.type,
        chatMessage.creatorType,
        chatMessage.content.toJson(),
        chatMessage.nickName,
    )

    fun toChatMessage(): ChatMessage {
        return ChatMessage(
            this.chatMessageKey.organizationId,
            this.uuid,
            this.chatMessageKey.seqId,
            this.createdAt,
            this.conversationId,
            this.from,
            this.to,
            this.type,
            this.creatorType,
            JsonUtils.fromJson(this.content),
            this.nickName,
        )
    }
}

@PrimaryKeyClass
data class ChatMessageKey(
    @PrimaryKeyColumn(name = "organization_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
    val organizationId: Int,
    /** 属于哪个用户，或者客服会话，或者客服组 **/
    @PrimaryKeyColumn(name = "owner_id", ordinal = 1, type = PrimaryKeyType.PARTITIONED)
    val ownerId: String,
    /** Ordered ID generated by the server */
    @PrimaryKeyColumn(name = "seq_id", ordinal = 2, type = PrimaryKeyType.CLUSTERED)
    val seqId: Long,
) : java.io.Serializable
